package com.work.straighttalk;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.work.straighttalk.adapter.EditBackPhotoAdapter;
import com.work.straighttalk.app.BaseActivity;
import com.work.straighttalk.app.StraightTalk;
import com.work.straighttalk.bean.User;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadBatchListener;
import cn.bmob.v3.listener.UploadFileListener;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * Created by dllo on 16/3/15.
 */
public class EditActivity extends BaseActivity {
    private static final int REQUEST_CODE_ALBUM = 1;
    private static final int REQUEST_CODE_CAMERA = 2;

    private static final int REQUEST_IMAGE = 2;
    @Bind(R.id.back_photo_recyclerview)
    RecyclerView backPhotoRecyclerview;
    @Bind(R.id.pic_content)
    RelativeLayout picContent;
    private ArrayList<String> mSelectPath;

    @Bind(R.id.baocun)
    Button baocun;
    @Bind(R.id.edit_content)
    EditText editContent;
    @Bind(R.id.open_layout)
    LinearLayout openLayout;
    @Bind(R.id.take_layout)
    LinearLayout takeLayout;

    String dateTime;

    private EditBackPhotoAdapter adp;
    private BmobFile bmobFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);
        adp = new EditBackPhotoAdapter();
        backPhotoRecyclerview.setLayoutManager(new GridLayoutManager(this, 3));
        backPhotoRecyclerview.setAdapter(adp);
    }

    @OnClick(R.id.baocun)
    protected void preservation() {

        String text = editContent.getText().toString();
        if (TextUtils.isEmpty(text)) {
            toast("内容不能为空");
            return;
        }
        if (targeturl == null) {
            publishWithoutFigure(text, null);
        } else {
            publish(text);
        }
    }

    @OnClick(R.id.open_layout)
    protected void openLayout() {
        int maxNum = 9;
        int selectedMode = MultiImageSelectorActivity.MODE_MULTI;

        Intent intent = new Intent(EditActivity.this, MultiImageSelectorActivity.class);
        selectedMode = MultiImageSelectorActivity.MODE_MULTI;
        // 最大可选择图片数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, maxNum);
        // 是否显示拍摄图片
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, false);
        // 选择模式
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, selectedMode);
        // 默认选择
        if (mSelectPath != null && mSelectPath.size() > 0) {
            intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, mSelectPath);
        }
        startActivityForResult(intent, REQUEST_IMAGE);

    }

    @OnClick(R.id.take_layout)
    protected void takeLayout() {
        Date date = new Date(System.currentTimeMillis());
        dateTime = date.getTime() + "";
        File f = new File(CacheUtils.getCacheDirectory(this, true,
                "pic") + dateTime);
        if (f.exists()) {
            f.delete();
        }
        try {
            f.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Uri uri = Uri.fromFile(f);
        Log.e("uri", uri + "");

        Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        camera.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(camera, REQUEST_CODE_CAMERA);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    /*
     * 发表带图片
	 */
    private void publish(final String commitContent) {
        // final BmobFile figureFile = new BmobFile(QiangYu.class, new
        // File(targeturl));
//        final BmobFile figureFile = new BmobFile(new File(targeturl));
//
//        figureFile.upload(this, new UploadFileListener() {
//
//            @Override
//            public void onSuccess() {
//                // TODO Auto-generated method stub
//                Log.i("EditActivity",
//                        "上传文件成功。" + figureFile.getFileUrl(EditActivity.this));
//                publishWithoutFigure(commitContent, figureFile);
//            }
//
//            @Override
//            public void onProgress(Integer arg0) {
//                // TODO Auto-generated method stub
//            }
//
//            @Override
//            public void onFailure(int arg0, String arg1) {
//                // TODO Auto-generated method stub
//            }
//        });


        int i = mSelectPath.size();
        String[] filePaths = new String[i];
        Log.d("EditActivity", "i:" + i);
        for (int j = 0; j < i; j++) {
            filePaths[j] = mSelectPath.get(j);
            bmobFile = new BmobFile(new File(String.valueOf(filePaths[j])));
        }

        Bmob.uploadBatch(this, filePaths, new UploadBatchListener() {
            @Override
            public void onSuccess(List<BmobFile> list, List<String> list1) {
                Log.d("EditActivity", list.get(0).getFileUrl(StraightTalk.getContext()));
                publishWithoutFigure(commitContent, bmobFile);
            }

            @Override
            public void onProgress(int i, int i1, int i2, int i3) {
            }

            @Override
            public void onError(int i, String s) {

            }
        });
    }

    private void publishWithoutFigure(final String commitContent,
                                      final BmobFile figureFile) {

        User user = BmobUser.getCurrentUser(this, User.class);
        final FriendsTexts friendsText = new FriendsTexts();
        friendsText.setName(user.getUsername());
        friendsText.setUser(user);
        friendsText.setText(commitContent);
        if (figureFile != null) {
            friendsText.setContentfigureurl(figureFile);
        }
        friendsText.setLove(0);

        friendsText.save(this, new SaveListener() {

            @Override
            public void onSuccess() {
                // TODO Auto-generated method stub
                setResult(RESULT_OK);
                finish();
            }

            @Override
            public void onFailure(int arg0, String arg1) {
                // TODO Auto-generated method stub
            }
        });
    }

    String targeturl = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);

                StringBuilder sb = new StringBuilder();
                for (String p : mSelectPath) {
                    sb.append(p);
                    sb.append("\n");
                }
                adp.loadData(mSelectPath);
                adp.notifyDataSetChanged();
                Log.d("EditActivity", "sb:" + sb);
//                mResultText.setText(sb.toString());
            }
        }
    }
}
